package com.picturestory.client.android.registration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import com.picturestory.client.android.util.Constants;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;

public class UserHttpRequester extends Activity {
	
	private static final String TAG = UserHttpRequester.class.getSimpleName();

	private static final int CHECK_DUPLICATE_USER_BY_ID_NUMBER = 1;
	private static final int CREATE_NEW_USER = 2;
	private static final int RETRIEVE_USER_BY_ID_NUMBER = 3;
	private static final int CHECK_DUPLICATE_USER_BY_USER_ID = 4;
	
	private static final String USER_URL = Constants.ROOT + "/user";
	private static final String CHECK_DUPLICATE_USER_URL = USER_URL + "/duplicate";
	private static final String CHECK_DUPLICATE_USER_BY_USER_ID_URL = USER_URL + "/duplicate/account";
	
	private Bundle extra;
	private String result;
	private String arg0;
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Log.i(Constants.LOGTAG, TAG + " : handleMessage to start UserInfo activity");
			Intent intent = new Intent(UserHttpRequester.this, UserInfo.class);
			intent.putExtra("result", result);
			setResult(1, intent);
			finish();
		}
		
	};
	
	private void foo(final String url, final String key, final String val) {
		new Thread() {
			@Override
			public void run() {
				result = getOnUserResource(url, key, val);
				mHandler.handleMessage(mHandler.obtainMessage());
			}
		}.start();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Intent intent = getIntent();
		
		extra = intent.getExtras();
		int which = intent.getIntExtra("which", -1);
		
		Log.i(Constants.LOGTAG, TAG + " : onCreate starts with which=" + which);
		
		switch(which) {
		case CHECK_DUPLICATE_USER_BY_ID_NUMBER:
			Log.i(Constants.LOGTAG, TAG + " : check duplicate user, create a new thread");
			foo(CHECK_DUPLICATE_USER_URL, "idNumber", getIntent().getStringExtra("idNumber"));
			
			break;
		case CHECK_DUPLICATE_USER_BY_USER_ID:
			foo(CHECK_DUPLICATE_USER_BY_USER_ID_URL, "userId", getIntent().getStringExtra("userId"));
			break;
		case CREATE_NEW_USER:
			
			break;
		case RETRIEVE_USER_BY_ID_NUMBER:
			foo(USER_URL, "idNumber", getIntent().getStringExtra("idNumber"));
			
			break;
		default:
			setResult(Constants.FAILED);
			finish();
			
		}
	}
	
	private String getOnUserResource(String url, String key, String val) {
		String result = null;
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = null;
        
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-type", "application/json");
        httpGet.setHeader("Charset", "UTF-8");
        httpGet.setHeader("Accept", "application/json");
        httpGet.setHeader(key, val);
        
        InputStream is = new InputStream() {
                @Override
                public int read() throws IOException {
                        return 0;
                }
        };
        
        Log.i(Constants.LOGTAG, TAG + " executes a GET method to " + url
        		+ " with header values (idNumber, " + extra.getString("idNumber") + ")");
        
        
        try {
            response = client.execute(httpGet);
            is = response.getEntity().getContent();
        } catch (ClientProtocolException e) {
        	e.printStackTrace();
        } catch (IOException e) {
        	e.printStackTrace();
        }
    
        Log.i(Constants.LOGTAG, TAG + " finishes executing a GET method; status=" + response.getStatusLine().getStatusCode()
        		);
    
        if (response.getStatusLine().getStatusCode() == 400) {
        	return null;
        }
    
        try {
            result = convertStreamToString(is);
        } catch (IOException e) {
        	e.printStackTrace();
            result = "You have failed!!";
        }
    
        Log.i(Constants.LOGTAG, TAG + " returns the result of a GET method = " + result);
        //mProgressDialog.dismiss();
        client.getConnectionManager().shutdown();
       	return result;
	}
	
	
	
	private String convertStreamToString(InputStream is) throws IOException {
        if (is != null) {
                Writer writer = new StringWriter();

                char[] buffer = new char[1024];
                try {
                        Reader reader = new BufferedReader(new InputStreamReader(
                                        is, "UTF-8"));
                        int n;
                        while ((n = reader.read(buffer)) != -1) {
                                writer.write(buffer, 0, n);
                        }
                } finally {
                        is.close();
                }
                return writer.toString();
        } else {
                return "";
        }
	}
}
